package com.shuzi.MediaShare.view;

import io.vov.vitamio.MediaPlayer;
import io.vov.vitamio.MediaPlayer.OnPreparedListener;
import io.vov.vitamio.widget.VideoView;
import android.app.Activity;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.media.AudioManager;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.shuzi.MediaShare.R;

/**
 * 自定义播放视频的视图
 * 
 * @author LUNG 下午2:19:00 2013
 */
public class MyVideoView extends RelativeLayout implements OnPreparedListener,
		OnGestureListener
{

	public VideoView videoView;

	private LinearLayout loadinglayout;

	public float VideoAspectRatio = 0;

	private GestureDetector detector;

	private Activity context;

	// private View mVolumeBrightnessLayout;
	// private ImageView mOperationBg;
	// private ImageView mOperationPercent;
	private AudioManager mAudioManager;

	/** 最大声音 */
	private int mMaxVolume;

	/** 当前声音 */
	private int mVolume = -1;

	/** 当前亮度 */
	private float mBrightness = -1f;

	public MyVideoView(Context context, AttributeSet attrs, int defStyle)
	{
		super(context, attrs, defStyle);
		initView(context);
	}

	public MyVideoView(Context context, AttributeSet attrs)
	{
		super(context, attrs);
		initView(context);
	}

	public MyVideoView(Context context)
	{
		super(context);
		initView(context);
	}

	/**
	 * 初始化视图
	 * 
	 * @param context
	 */
	private void initView(Context context)
	{
		View view = View.inflate(context, R.layout.media_play, null);
		videoView = (VideoView) view.findViewById(R.id.videoView);
		loadinglayout = (LinearLayout) view
				.findViewById(R.id.viedo_loading_layout);
		setGravity(Gravity.CENTER);
		setBackgroundColor(Color.BLACK);
		addView(view);
		detector = new GestureDetector(this);
		mAudioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
		mMaxVolume = mAudioManager
				.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
		setOnTouchListener(new OnTouchListener()
		{

			@Override
			public boolean onTouch(View v, MotionEvent event)
			{
				// if (detector.onTouchEvent(event))
				// return true;
				//
				// // 处理手势结束
				// switch (event.getAction() & MotionEvent.ACTION_MASK)
				// {
				// case MotionEvent.ACTION_UP:
				// endGesture();
				// break;
				// }
				// return false;
				return detector.onTouchEvent(event);
			}
		});
	}

	/**
	 * // * 播放视频
	 * 
	 * @param context
	 * @param path
	 */
	public void startPlayVideo(Context context, String path)
	{
		this.context = (Activity) context;
		if (path != null)
		{
			videoView.setVideoPath(path);
			videoView.setOnPreparedListener(this);
			videoView.setVideoQuality(MediaPlayer.VIDEOQUALITY_HIGH);
			videoView
					.setMediaController(new io.vov.vitamio.widget.MediaController(
							context));
			// videoView.setVideoLayout(VideoView.VIDEO_LAYOUT_ORIGIN, 0);
			videoView.setWillNotCacheDrawing(false);
		} else
		{
			Toast.makeText(context, "播放地址为空", Toast.LENGTH_SHORT).show();
		}
	}

	@Override
	public void onPrepared(MediaPlayer mp)
	{
		if (context !=null)
		{
			context.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
		}
		if (loadinglayout != null)
		{
			loadinglayout.setVisibility(View.GONE);
			VideoAspectRatio = videoView.getVideoAspectRatio();
			System.out.println(videoView.getVideoAspectRatio());
			mp.start();
		}

	}

	@Override
	public boolean onDown(MotionEvent e)
	{
		// TODO Auto-generated method stub
		return true;
	}

	@Override
	public void onShowPress(MotionEvent e)
	{
		// TODO Auto-generated method stub

	}

	@Override
	public boolean onSingleTapUp(MotionEvent e)
	{
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
			float distanceY)
	{
		float mOldX = e1.getX(), mOldY = e1.getY();
		int y = (int) e2.getRawY();
		DisplayMetrics disp = context.getResources().getDisplayMetrics();
		int windowWidth = disp.widthPixels;
		int windowHeight = disp.heightPixels;

		if (mOldX > windowWidth * 4.0 / 5)// 右边滑动
			onVolumeSlide((mOldY - y) / windowHeight);
		else if (mOldX < windowWidth / 5.0)// 左边滑动
			onBrightnessSlide((mOldY - y) / windowHeight);

		// return super.onScrollChanged(e1, e2, distanceX, distanceY);
		return false;
	}

	@Override
	public void onLongPress(MotionEvent e)
	{
		// TODO Auto-generated method stub

	}

	@Override
	public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
			float velocityY)
	{
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean onTouchEvent(MotionEvent event)
	{
		/*
		 * if (detector.onTouchEvent(event)) return true;
		 * 
		 * // 处理手势结束 switch (event.getAction() & MotionEvent.ACTION_MASK) { case
		 * MotionEvent.ACTION_UP: endGesture(); break; }
		 */
		return super.onTouchEvent(event);
	}

	/** 手势结束 */
	private void endGesture()
	{
		mVolume = -1;
		mBrightness = -1f;

		// 隐藏
		mDismissHandler.removeMessages(0);
		mDismissHandler.sendEmptyMessageDelayed(0, 500);
	}

	/** 定时隐藏 */
	private Handler mDismissHandler = new Handler()
	{
		@Override
		public void handleMessage(Message msg)
		{
			// mVolumeBrightnessLayout.setVisibility(View.GONE);
		}
	};

	/**
	 * 滑动改变声音大小
	 * 
	 * @param percent
	 */
	private void onVolumeSlide(float percent)
	{
		if (context == null)
		{
			return;
		}
		if (mVolume == -1)
		{
			mVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
			if (mVolume < 0)
				mVolume = 0;

			// 显示
			// mOperationBg.setImageResource(R.drawable.video_volumn_bg);
			// mVolumeBrightnessLayout.setVisibility(View.VISIBLE);
		}

		int index = (int) (percent * mMaxVolume) + mVolume;
		if (index > mMaxVolume)
			index = mMaxVolume;
		else if (index < 0)
			index = 0;

		// 变更声音
		mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, index, 0);

		// 变更进度条
		// ViewGroup.LayoutParams lp = mOperationPercent.getLayoutParams();
		// lp.width = findViewById(R.id.operation_full).getLayoutParams().width
		// * index / mMaxVolume;
		// mOperationPercent.setLayoutParams(lp);
	}

	/**
	 * 滑动改变亮度
	 * 
	 * @param percent
	 */
	private void onBrightnessSlide(float percent)
	{
		if (context == null)
		{
			return;
		}
		if (mBrightness < 0)
		{
			mBrightness = context.getWindow().getAttributes().screenBrightness;
			if (mBrightness <= 0.00f)
				mBrightness = 0.50f;
			if (mBrightness < 0.01f)
				mBrightness = 0.01f;

			// 显示
			// mOperationBg.setImageResource(R.drawable.video_brightness_bg);
			// mVolumeBrightnessLayout.setVisibility(View.VISIBLE);
		}
		WindowManager.LayoutParams lpa = context.getWindow().getAttributes();
		lpa.screenBrightness = mBrightness + percent;
		if (lpa.screenBrightness > 1.0f)
			lpa.screenBrightness = 1.0f;
		else if (lpa.screenBrightness < 0.01f)
			lpa.screenBrightness = 0.01f;
		context.getWindow().setAttributes(lpa);

		// ViewGroup.LayoutParams lp = mOperationPercent.getLayoutParams();
		// lp.width = (int)
		// (findViewById(R.id.operation_full).getLayoutParams().width *
		// lpa.screenBrightness);
		// mOperationPercent.setLayoutParams(lp);
	}

}
